package cn.chinaunicom.admin.config;

import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cn.chinaunicom.admin.interceptor.AppInterceptor;
import cn.chinaunicom.fast.common.filter.XssFilter;
import cn.chinaunicom.fast.common.interceptor.UserInterceptor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class WebServerMvcConfigurerAdapter implements WebMvcConfigurer {

    @Value("${easySecret.userInterceptor.enabled:true}")
    private Boolean enabled;

    @Value("${easySecret.userInterceptor.reject:false}")
    private Boolean reject;

    @Bean
    public HandlerInterceptor userInterceptor() {
        UserInterceptor userInterceptor = new UserInterceptor(reject);
        return userInterceptor;
    }

    @Bean
    public HandlerInterceptor appInterceptor() {
        AppInterceptor appInterceptor = new AppInterceptor();
        return appInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 用户拦截器
        if(enabled) {
            registry.addInterceptor(userInterceptor())
                .excludePathPatterns("/easy/**");
        }

        // 应用拦截器
        registry.addInterceptor(appInterceptor())
                .addPathPatterns(Stream.of("/easy/**").collect(Collectors.toList()));
    }

    /**
     * 注册xss过滤器
     * @return
     */
//    @Bean
//    public FilterRegistrationBean<XssFilter> filterRegistrationBean(){
//        FilterRegistrationBean<XssFilter> registrationBean = new FilterRegistrationBean<>(new XssFilter());
//        //过滤所有路径
//        registrationBean.addUrlPatterns("/*");
//        //添加不过滤路径
//        registrationBean.setName("xssFilter");
//        registrationBean.setOrder(1);
//        log.info("xssFilter init success!");
//        return registrationBean;
//    }
}
